const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaBody = require('koa-body')
const path = require('path')

const index = require('./routes/index')
const users = require('./routes/users')
const oss = require('./routes/oss')

// error handler
onerror(app)

app.use(
  koaBody({
    multipart: true, //解析多个文件
    formidable: {
      // maxFileSize: 100 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      //uploadDir: 可以填写一个路径，不填写默认为 os.tmpDir()
      uploadDir: path.join(__dirname, 'public/images/'),
      // 保持后缀名
      keepExtensions: true,
      onError(err) {
        console.log(err)
      }
    }
  })
)
// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text']
  })
)

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
  views(__dirname + '/views', {
    extension: 'pug'
  })
)

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(oss.routes(), oss.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
